﻿using AutoMapper;
using B.Rabbit.DataBase.Domain;
using B.Rabbit.DataBase.ErrorCode;
using B.Rabbit.DataBase.Infrastructure.Infrastructure;
using B.Rabbit.DataBase.Read.Api.Applocation.Command.Rabbit.Traceab;
using B.Rabbit.DataBase.Read.Api.Applocation.Handler.Login;
using MediatR;

namespace B.Rabbit.DataBase.Read.Api.Applocation.Handler.Rabbit.Traceab
{
    public class UpdateTraceabCommandHandler : IRequestHandler<UpdateTraceabCommand, ApiResult<int>>
    {
        private readonly ILogger<UpdateTraceabCommandHandler> _logger;
        IBaseRepository<TraceabilityModel> traceabmodel;
        IMapper mapper;

        public UpdateTraceabCommandHandler(ILogger<UpdateTraceabCommandHandler> logger, IBaseRepository<TraceabilityModel> traceabmodel, IMapper mapper)
        {
            _logger = logger;
            this.traceabmodel = traceabmodel;
            this.mapper = mapper;
        }
        /// <summary>
        /// 溯源信息更新操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(UpdateTraceabCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var traceab = await traceabmodel.GetValue(request.Id);
            var entity = mapper.Map(request,traceab);
            var updatetraceab = await traceabmodel.UpdateAsync(entity);
            if (updatetraceab > 0)
            {
                res.msg = "修改成功";
                res.code = StatusCode.Ok;
                res.data = updatetraceab;
            }
            else
            {
                res.msg = "修改失败";
                res.code = StatusCode.Fail;
                res.data = updatetraceab;
            }
            return res;
        }
    }
}
